const host='http://localhost:3000'

function btnAdd() {
    console.log('新增');
    location.href='./addOrEdit.html'

}
function btnEdit() {
    console.log('编辑');
    location.href = './addOrEdit.html'

}
async function btnFilter() {
    console.log('过滤');
    let keyword = $('input[name=keyword]').val()

    let res= await axios.get(`${host}/blogs?keyword=${keyword}`)
    let blogs = res.data.data;

    $('tr[class^=blog]').remove();
    blogs.forEach(item => {
        let html = `
                        <tr class="blog${item.id}">
                                <td>${item.id}</td>
                                <td>${item.title}</td>
                                <td>${item.author}</td>
                                <td>
                                    <input type="button" value="编辑" onclick=btnEdit(${item.id})>
                                    <input type="button" value="删除" onclick=btnDel(${item.id})>
                                </td>
                            </tr>
                        `
        $('tbody').append(html)
    });

}
function btnDel() {
    console.log('删除');
    if (confirm("确定要删除吗")) {
        axios.delete(`${host}/blogs/${id}`).then((res)=>{
            let data =res.data;
            if (data.code) {
                let tr =document.querySelector(`.blog${id}`)
                tr.remove()
            }else{
                confirm(`${data.msg}`)
            }
        })
    }


}
function btnSave() {
    console.log('保存');
    let id =new URLSearchParams(location.search).get('id')||0

    let title=$('input[name=title]').val();
    let author = $('input[name=author]').val();

    title=title.trim()
    author=author.trim()
    let obj ={
        title,author
    }
    console.log(obj);
    if(id>0){
        axios.put(`${host}/blogs`,obj).then((res)=>{
            if (res.data.code===1000) {
                location.href='./index.html'
            }else{
                confirm(res.data.msg)
            }
        })
    }else{
        //第二步
        axios.post(`${host}/blogs`,obj).ther((res)=>{
            if (res.data.code===1000) {
                location.href='./index.html'
                
            }else{
                confirm(res.data.msg)
            }
        })
    }
    

}
function btnCancel() {
    console.log('取消');
    location.href='./index.html'

}
